package service

import (
	"database/sql"
	"dujitang/src/config"
	"dujitang/src/model"

	// mysql is driver
	_ "github.com/go-sql-driver/mysql"
)

var db *sql.DB

func init() {
	var err error
	db, err = sql.Open("mysql", config.SQLDB)
	if err != nil {
		panic(err)
	}

	return
}

// Index is 毒鸡汤
func Index() (*model.Soul, error) {
	var soul model.Soul
	err := db.QueryRow("select * from soul order by rand( ) limit 1").Scan(&soul.ID, &soul.Title, &soul.Hits)
	// 判断是否错误，如果有直接返回了
	config.CheckErr(err)

	AddClick(soul.ID, soul.Hits)

	return &soul, nil
}

// AddClick is 添加点击率
func AddClick(ID int, Hits int) (bool, error) {

	num := Hits + 1

	res, err := db.Exec("update soul set Hits=? where ID=?", num, ID)
	config.CheckErr(err)

	result, err := res.RowsAffected()
	config.CheckErr(err)

	return result > 0, nil
}
